<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/5/18
 * Time: 下午6:09
 */

namespace App\Http\Model;

use App\Lib\faceid;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Table extends Base
{

    private $tableInValKey = 'TABLE:INVAL:';
    private $tableOutValKey = 'TABLE:OUTVAL:';
    private $tablePearlUsedKey = 'TABLE:PEARLUSED:';
    private $tableFirstPrizePoolKey = 'TABLE:FIRSTPRIZEPOOL:';
    protected $tableTable = 'table';
    protected $tableLogTable = 'table_log';
    protected $tablePollTable = 'table_poll';
    protected $tableCouponTable = 'table_coupon';
    protected $tableCouponLogTable = 'table_coupon_log';
    protected $tableFirstPrizePoolTable = 'table_first_prize_pool';

    protected $tablePrimaryKey = 'table_id';
    protected $tableLogPrimaryKey = 'table_log_id';
    protected $tablePollPrimaryKey = 'table_poll_id';
    protected $tableCouponPrimaryKey = 'table_coupon_id';
    protected $tableCouponLogPrimaryKey = 'table_coupon_log_id';


    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /*
     * table表相关
     * */

    /**
     * 获取转盘根据转盘IDs
     * @param $tableIds
     * @return array|mixed
     */
    public function getTableByIds($tableIds){
        $result = DB::table($this->tableTable)
            ->whereIn("table_id", $tableIds)
            ->get(['table_id','name','image','explain','ratio', 'status']);
        if (empty($result)){
            return [];
        }
        $result = $this->objToArray($result);
        for ($i = 0; $i < count($result); $i++) {
            $result[$i]['image'] = getPicDomain() . $result[$i]['image'];
        }
        return $result;
    }

    /**
     * getTableByActivityId
     * @param $activityId
     * @return array|mixed
     */
    public function getTableByActivityId($activityId){
        $result = DB::table($this->tableTable)
            ->where("activity_id", "=", $activityId)
            ->get(['table_id','name','image','explain','ratio', 'status']);
        if (empty($result)){
            return [];
        }
        $result = $this->objToArray($result);
        for ($i = 0; $i < count($result); $i++) {
            $result[$i]['image'] = getPicDomain() . $result[$i]['image'];
        }
        return $result;
    }

    /**
     * 获取转盘
     * @param $tableId
     * @return array|mixed
     */
    public function getTableById($tableId){
        $result = DB::table($this->tableTable)
            ->where($this->tablePrimaryKey, '=', $tableId)
            ->first(['table_id','name','image','explain','ratio', 'status', 'price', 'pearl_price', 'pearl_limit_num']);
        if (empty($result)){
            return [];
        }
        $result = $this->objToArray($result);
        $result['image'] = getPicDomain() . $result['image'];
        return $result;
    }





    /**
     * 转盘-创建/更新/删除
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @param int $tableId 转盘ID
     * @return bool
     * */
    public function CUDTable($data = [], $type = 'insert', $tableId = 0)
    {
        switch ($type) {
            case 'insert':
                $ret = DB::table($this->tableTable)->insertGetId($data);
                break;
            case 'update':
                $ret = DB::table($this->tableTable)->where([$this->tablePrimaryKey => $tableId])->update($data);
                break;
            case 'delete':
                $ret = DB::table($this->tableTable)->where([$this->tablePrimaryKey => $tableId])->delete();
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }



    /*
     * table_poll 表相关
     * */

    /**
     * 获取转盘的奖池
     * @param $tableId
     * @return array|mixed
     */
    public function getTablePollByTableId($tableId){
        $result = DB::table($this->tablePollTable)
            ->where('table_id', '=', $tableId)
            ->get(["table_poll_id", "data_id", "data_type", "data_name", "data_image", "num", "probability", "data_price", "data_score", "table_id","data_image2"]);
        if (empty($result)){
            return [];
        }

        $result = $this->objToArray($result);

        for ($i = 0; $i < count($result); $i++) {
            $result[$i]['data_image'] = getPicDomain() . $result[$i]['data_image'];
            $result[$i]['data_image2'] = getPicDomain() . $result[$i]['data_image2'];
        }

        return $result;
    }


    /**
     * 根据ID获取
     *
     * @param int $tablePollId ID
     * @return array
     * */
    public function getTablePollById($tablePollId)
    {
        $db = DB::table($this->tablePollTable);
        $getData = $db->where([$this->tablePollPrimaryKey => $tablePollId])->first();
        return self::objToArray($getData);
    }

    /**
     * 根据IDS获取
     *
     * @param int $tablePollIds IDs
     * @return array
     * */
    public function getTablePollByIds($tablePollIds)
    {
        $db = DB::table($this->tablePollTable);
        $result = $db->whereIn("table_poll_id", $tablePollIds)->get(["table_poll_id","data_type","data_name","data_id","data_image", "data_price", "data_score"]);

        if (empty($result)){
            return [];
        }

        $result = $this->objToArray($result);

        for ($i = 0; $i < count($result); $i++) {
            $result[$i]['data_image'] = getPicDomain() . $result[$i]['data_image'];
        }

        return $result;
    }

    /**
     * 转盘几率-创建/更新/删除
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @param int $tablePollId 转盘ID
     * @return bool
     * */
    public function CUDTablePoll($data = [], $type = 'insert', $tablePollId = 0)
    {
        switch ($type) {
            case 'insert':
                $ret = DB::table($this->tablePollTable)->insertGetId($data);
                break;
            case 'update':
                $ret = DB::table($this->tablePollTable)->where([$this->tablePollPrimaryKey => $tablePollId])->update($data);
                break;
            case 'delete':
                $ret = DB::table($this->tablePollTable)->where([$this->tablePollPrimaryKey => $tablePollId])->delete();
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }

    /**
     * 根据转盘ID删除奖品几率配置
     *
     * @param int $tableId ID
     * @return array
     * */
    public function removeBoxPollByTableId($tableId)
    {
        return $ret = DB::table($this->tablePollTable)->where(["table_id" => $tableId])->delete();
    }

    /*
     * table_log 表相关
     * */

    /**
     * 添加用户转盘记录
     *
     * @return array
     * */
    public function addTableLog($tableId, $dataId, $dataType, $userId, $num, $roomId, $tablePollId, $propLogId = 0, $second = 0){
        return DB::table($this->tableLogTable)->insertGetId([
            'table_id' => $tableId,
            'data_id' => $dataId,
            'data_type' => $dataType,
            'user_id' =>$userId,
            'num' => $num,
            'create_time' => time(),
            'room_id' => $roomId,
            'table_poll_id' => $tablePollId,
            'prop_log_id' => $propLogId,
            'second' => $second
        ]);
    }

    /**
     * 根据转盘ID 获取用户记录
     *
     * @param int $tableIds ID
     * @return array
     * */
    public function getTableLogByTableId($tableIds, $skip = 0, $limit = 10){
        $result = DB::table($this->tableLogTable)
            ->whereIn('table_id', $tableIds)
            ->orderBy($this->tableLogPrimaryKey, "desc")
            ->skip($skip)
            ->limit($limit)
            ->get();
        return $this->objToArray($result);
    }

    /**
     * 根据转盘ID、用户ID 获取用户记录
     *
     * @param int $tableIds IDs
     * @param int $type 0为查询本人 1为所有人
     * @return array
     * */
    public function getTableLogByTableIdAndUserId($tableIds, $userId, $skip = 0, $limit = 20, $type = 0){
        $where = $type == 0 ? ['user_id' => $userId] : [];
        $result = DB::table($this->tableLogTable)
            ->whereIn('table_id', $tableIds)
            ->where($where)
            ->orderBy($this->tableLogPrimaryKey, "desc")
            ->skip($skip)
            ->limit($limit)
            ->get();
        return $this->objToArray($result);
    }

    /**
     * 根据ID获取
     *
     * @param int $tableLogId ID
     * @return array
     * */
    public function getTableLogById($tableLogId)
    {
        $db = DB::table($this->tableLogTable);
        $getData = $db->where([$this->tableLogPrimaryKey => $tableLogId])->first();
        return self::objToArray($getData);
    }

    /**
     * 根据ID获取
     *
     * @param int $tableLogId ID
     * @param array $data 更新数据
     * @return array
     * */
    public function updateTableLogById($tableLogId, $data)
    {
        return $ret = DB::table($this->tableLogTable)->where([$this->tableLogPrimaryKey => $tableLogId])->update($data);
    }



    /*
     * table_coupon
     */
    /**
     * 根据转盘ID、用户ID 获取用户记录
     *
     * @param int $tableId ID
     * @return array
     * */
    public function getTableCouponByUserId($tableId, $userId){
        $result = DB::table($this->tableCouponTable)
            ->where('table_id', '=', $tableId)
            ->where('user_id', '=', $userId)
            ->first();
        return $this->objToArray($result);
    }

    public function incrTableCoupon($userId, $tableId, $num)
    {
        $result = DB::table($this->tableCouponTable)
            ->where('table_id', '=', $tableId)
            ->where('user_id', '=', $userId)
            ->first();

        if ($result) {
            $incrRet = DB::table($this->tableCouponTable)
                ->where(['user_id' => $userId, 'table_id' => $tableId])
                ->where("num", ">=", 0)
                ->increment('num', $num, ['update_time'=>time()]);

            if (!$incrRet) {
                return false;
            }
            return true;
        } else {
            DB::table($this->tableCouponTable)->insertGetId([
                "user_id" => $userId,
                "table_id" => $tableId,
                "num" => $num,
                "create_time" => time()
            ]);
            return true;
        }
    }

    //$tableCouponLogType = 1  默认是钻石支付来源  2:金豆支付来源
    public function createTableCouponLog($userId, $tableId, $num, $tableCouponLogType = 1)
    {
        $tableCoupon = DB::table($this->tableCouponTable)
            ->where('table_id', '=', $tableId)
            ->where('user_id', '=', $userId)
            ->first();

        $avail = $tableCoupon ? $tableCoupon->num : 0;

        // 参数
        $diamondParams = [
            "table_id" => $tableId,
            "user_id" => $userId,
            "change" => $num,
            "avail" => $avail,
            "type" => $tableCouponLogType,
            "create_time" => time()
        ];

        $insertRet = DB::table($this->tableCouponLogTable)->insertGetId($diamondParams);

        return $insertRet;
    }


    /*
     * 其他相关
     * */
    public function incInVal($tableId, $val){
        return Redis::INCRBY($this->tableInValKey . $tableId, $val);
    }

    public function getInVal($tableId){
        $val = Redis::GET($this->tableInValKey . $tableId);
        if (empty($val)){
            return 0;
        }
        return intval($val);
    }

    public function incOutVal($tableId, $val){
        return Redis::INCRBY($this->tableOutValKey . $tableId, $val);
    }

    public function getOutVal($tableId)
    {
        $val = Redis::GET($this->tableOutValKey . $tableId);
        if (empty($val)) {
            return 0;
        }
        return intval($val);
    }

    //获取用户当天金豆支付次数
    public function getUserPearlpayNum($userId)
    {
        $today = date('Ymd');
        $userHas = Redis::HGET($this->tablePearlUsedKey.$userId, $today);
        return $userHas ?? 0;
    }

    //增加用户当天金豆购买次数
    public function setUserPearlpayNum($userId, $num)
    {
        $today = date('Ymd');
        Redis::HINCRBY($this->tablePearlUsedKey.$userId, $today, $num);
    }

    //生成一等奖奖池
    public function makeFirstPrizePool($tableId)
    {
        if(Redis::llen($this->tableFirstPrizePoolKey.$tableId) == 0) {
            $tableFirstPrizePoolList = DB::table($this->tableFirstPrizePoolTable)
                ->where('table_id', '=', $tableId)
                ->where('is_default', '=', 0)
                ->get();
            $poolList = self::objToArray($tableFirstPrizePoolList);
            if(empty($poolList)) {
                return false;
            }

            shuffle($poolList);
            foreach ($poolList as $v) {
                Redis::lpush($this->tableFirstPrizePoolKey.$tableId, $v['id']);
            }
            return true;
        }
        return false;
    }

    //从一等奖奖池中取一个出来
    public function getFirstPrizeOne($tableId)
    {
        $val = Redis::lpop($this->tableFirstPrizePoolKey.$tableId);
        //获取一等奖奖池奖品信息
        $prizeItem = DB::table($this->tableFirstPrizePoolTable)
            ->where('id', '=', $val)
            ->where('is_default', '=', 0)
            ->first(['data_type', 'data_id', 'data_name', 'data_image', 'id']);
        //抽完奖用默认的一等奖奖品
        if(empty($prizeItem)) {
            $prizeItem = DB::table($this->tableFirstPrizePoolTable)
                ->where('table_id', '=', $tableId)
                ->where('is_default', '=', 1)
                ->first(['data_type', 'data_id', 'data_name', 'data_image', 'id']);
        }
        return self::objToArray($prizeItem);
    }

    //根据tableId，dataId 与 userId 获取用户纪录
    public function getTableLogByUserId($tableId, $userId, $dataId)
    {
        $result = DB::table($this->tableLogTable)
            ->where('table_id', '=', $tableId)
            ->where('user_id', '=', $userId)
            ->where('data_id', '=', $dataId)
            ->first();
        return $this->objToArray($result);
    }
}
